package com.spring.component.link;

public class LinkFactory {

  /**
   * 按入参顺序构建单向列表
   * 
   * @param ts
   * @param <T>
   * @return
   */
  public static <T> SingleNode<T> buildSingleNode(T... ts) {
    SingleNode singleNode = new SingleNode(null, ts[ts.length - 1]);
    for (int i = ts.length - 2; i >= 0; i--) {
      singleNode = new SingleNode(singleNode, ts[i]);
    }
    return singleNode;
  }

  /**
   * 按入参顺序逆序构建单向列表
   * 
   * @param ts
   * @param <T>
   * @return
   */
  public static <T> SingleNode<T> buildReverseSingleNode(T... ts) {
    SingleNode singleNode = new SingleNode(null, ts[0]);
    for (int i = 1; i < ts.length; i++) {
      singleNode = new SingleNode(singleNode, ts[i]);
    }
    return singleNode;
  }

  /**
   * 按入参顺序逆序构建双向列表
   * 
   * @param ts
   * @param <T>
   * @return
   */
  public static <T> DupleNode<T> buildDupleNode(T... ts) {
    DupleNode dupleNode = new DupleNode(null, null, ts[ts.length - 1]);
    DupleNode prev = new DupleNode(null, dupleNode, ts[ts.length - 2]);;
    for (int i = ts.length - 3; i >= 0; i -= 2) {
      dupleNode.setPrev(prev);
      dupleNode = new DupleNode(null, prev, ts[i]);
      prev.setPrev(dupleNode);
      if (i > 0) {
        prev = new DupleNode(null, dupleNode, ts[i - 1]);
      }

    }
    return dupleNode;
  }

  /**
   * 构建完全闭环链表
   * 
   * @param ts
   * @param <T>
   * @return
   * @throws Exception
   */
  public static <T> DupleNode<T> buildRingDupleNode(T... ts) throws Exception {
    DupleNode dupleNode = buildDupleNode(ts);
    if (dupleNode.isHavRing()) {
      throw new Exception("链表中已经存在闭环");
    }
    dupleNode.setPrev(dupleNode.getLastNode());
    dupleNode.getLastNode().setNext(dupleNode);
    return dupleNode;
  }

}
